package com.walker.elk.netty.socket.server;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

public class WalkerNettyServerChannelHandler extends SimpleChannelInboundHandler<String> {

	static int i = 1;

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.getStackTrace();
		ctx.close();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		try {
			System.out.println("===================================server received message:"
					+ ctx.channel().remoteAddress() + msg);
			if (i < 10) {
				ctx.writeAndFlush("server walker send message" + i);
				i++;
			}
			ChannelFuture channelFuture = ctx.channel().writeAndFlush(msg);
			channelFuture.addListener(ChannelFutureListener.CLOSE);
		} finally {
			//释放消息
			ReferenceCountUtil.release(msg);
		}
		
		//写数据一般使用ByteBuf（posation不用考虑，Netty封装已经处理）  工具类 Unpooled
		
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
	}

	
}
